package com.example.goandroiddemo.http;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.chouren.goandroid.http.android.async.AsyncExecutor;
import com.chouren.goandroid.util.Logger;
import com.example.goandroiddemo.R;

public class AsyncExecutorTest extends Activity {
	private TextView mtextView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_async_executor_test);
		
		mtextView = (TextView)findViewById(R.id.textview1);
		
		mtextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(AsyncExecutorTest.this, "hahah", Toast.LENGTH_SHORT).show();
			}
		});
		
		test();
	}
	
	public void test() {
		AsyncExecutor asyncExecutor = new AsyncExecutor();
		asyncExecutor.execute(new AsyncExecutor.AsyncTask<Integer>() {
			@Override
			public Integer doInBackground() {
				Logger.debug(null, "doInBackground");
				return doingSothing();
			}
			
			@Override
			public void onPostExecute(Integer data) {
				Logger.debug(null, "onPostExecute");
				mtextView.setText("result:" + data);
			}
			
			@Override
			public void onFailExecute() {
				Logger.debug(null, "onPostExecute");
				mtextView.setText("result: error");
			}
		});
		
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		asyncExecutor.shutdownNow();
	}
	
	public int doingSothing() {
		int i = 0;
		while(i < 10) {
			Logger.debug(null, "doingSothing:" + i);
			i++;
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return i;
	}
	
	public void testError() {
		mtextView.setText("result:" + doingSothing());
	}
}
